package com.duqc.designpattern.responsibility;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ResponsibilityChain
 * @Description 责任链模式
 * @Author duqc
 * @Date 2021/5/7
 **/
@Slf4j
public class ResponsibilityChain {

    public static void main(String[] args) {
//        String data = "肉蛋葱鸡水果蔬菜千层饼雅俗共赏第五层的马老师";
//
//        Request request = new Request();
//        request.setData(data);
//
//        String requestData = request.getData();
//
//        if (requestData.contains("水果")) {
//            requestData = filterByWord(requestData, "水果");
//        }
//        if (requestData.contains("蔬菜")) {
//            requestData = filterByWord(requestData, "蔬菜");
//        }
//        request.setData(requestData);
//        log.info(requestData);

        String data = "肉蛋葱鸡水果蔬菜千层饼雅俗共赏第五层的马老师";

        Request request = new Request();
        request.setData(data);

        //创建FilterChain执行链
        FilterChain filterChain = new FilterChain();
        //添加过滤器
        filterChain.addFilter(new FruitsFilter());
        filterChain.addFilter(new VegetablesFilter());
        //执行预处理
        String s = filterChain.prehandleRequest(request.getData());
        request.setData(s);
        log.info(request.getData());

    }

    /**
     * 过滤关键字的方法
     *
     * @param requestData
     * @param word
     * @return String
     */
    private static String filterByWord(String requestData, String word) {
        StringBuilder stringBuilder = new StringBuilder(requestData);
        while (true) {
            int index = stringBuilder.indexOf(word);
            if (index != -1) {
                for (int i = 0; i < word.length(); i++) {
                    stringBuilder.deleteCharAt(index);
                }
            } else {
                break;
            }
        }
        return stringBuilder.toString();
    }

}
